import { useCallback, useEffect, useRef, useState } from "react"
import soltObserver from "../utils/soltObserver";

function useIntersectionObserver(options, targetList) {
  const observeRef = useRef(null);
  const [observe, setObserve] = useState(targetList?.map(it => ({ targetId: `chart_${it}`, isIntersecting: false })))

  const changeValue = useCallback((newValue) => {
    setObserve(newValue)
  }, [])

  const initState = async () => {
    try {
      observeRef.current = new soltObserver(options, targetList, changeValue)
    } catch (e) {
      console.error('IntersectionObserver实例失败', e)
    }
  }

  useEffect(() => {
    initState();
    return () => {
      if (observeRef.current) observeRef.current = null
    }
  }, [])

  return observe
}

export default useIntersectionObserver